package cn.jetpiece.cloud.common.app.modular.websocket.handler;

import cn.hutool.core.util.StrUtil;
import cn.jetpiece.cloud.common.app.modular.websocket.manager.WebSocket;
import cn.jetpiece.cloud.model.contants.CommonSendStatus;
import cn.jetpiece.cloud.redis.listener.JetpieceRedisListener;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author XuJZ
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SocketMessageHandler implements JetpieceRedisListener {
    private final WebSocket webSocket;

    @Override
    public void onMessage(JSONObject message) {
        log.info(message.toString());
        Long tenantId = message.getLong("tenantId");
        String username = message.getString("username");
        String messageInfo = message.getString("message");
        /* 全员消息 */
        if (tenantId == null && StrUtil.isBlank(username)) {
            webSocket.pushMessage(messageInfo);
            return;
        }
        /* 用户为空发送给租户下所有用户 */
        if (StrUtil.isBlank(username)) {
            webSocket.pushMessage(tenantId, messageInfo);
            //app端消息推送
            webSocket.pushMessage(tenantId,username + CommonSendStatus.APP_SESSION_SUFFIX, messageInfo);
            return;
        }
        webSocket.pushMessage(tenantId, username, messageInfo);
        //app端消息推送
        webSocket.pushMessage(tenantId, username + CommonSendStatus.APP_SESSION_SUFFIX, messageInfo);
    }
}
